/**
 * 
 */
package com.wgo.precise.server.web.servlet;

import javax.servlet.ServletContextEvent;

import com.wgo.bpot.server.persist.Persistent;
import com.wgo.bpot.server.persist.hibernate.HibernatePersistService;
import com.wgo.bpot.server.web.listener.HibernateListener;
import com.wgo.bpot.wiring.InitializationService;
import com.wgo.bpot.wiring.ServiceAccessor;
import com.wgo.precise.wiring.PreciseWiringImpl;

/**
 * @author Petter L. H. Eide
 * @version $Id: PreciseServletContextListener.java 540 2008-01-09 19:42:31Z petter.eide $
 */
public class PreciseServletContextListener extends HibernateListener {

	/* (non-Javadoc)
	 * @see com.wgo.bpot.server.web.listener.HibernateListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	@Override
	public void contextInitialized(ServletContextEvent event) {
		super.contextInitialized(event);
		ServiceAccessor<Persistent, HibernatePersistService<Persistent>> serviceAccessor = new PreciseWiringImpl().getServiceAccessor();
		InitializationService initializationService = serviceAccessor.getInitializationService();
		if ( null != initializationService ) {
			try {
				serviceAccessor.getPersistService().startTransaction();
				if (initializationService.isInitializationNeeded()) {
					initializationService.initialize();
				} else {
					initializationService.updateUsersFromFile();
				}
				serviceAccessor.getPersistService().commitTransaction();
			} catch (Throwable t) {
				log.error("PreciseServletContextListener: Error trying to initialize.. ", t);
				serviceAccessor.getPersistService().rollbackTransaction();
			}
			return;
		}
		log.warn("InitalizationService not available");
	}

}
